<?php

namespace App\Admin\Eloquent;
use App\Exceptions\BusinessException;
use App\Admin\Eloquent\GiftActivity;
use App\Eloquent\TradeRecords;
use App\Admin\Eloquent\GiftReceive;
use App\Admin\Eloquent\Profit;
use App\Admin\Eloquent\ProjectsUser;
use App\Admin\Eloquent\Code;
use App\Admin\Eloquent\User;
use App\Admin\Eloquent\ProjectTypeTemplate;
use App\Admin\Eloquent\ProjectTypeTemplateAttribute;
use App\Admin\Eloquent\Information;
use App\Admin\Eloquent\ProjectAttr;
use CreateP2pHostingBorrowingTarget;
use Router;
use DB;
use Log;
use CancelPreAuthTrade;
use CreateSingleHostingPayTrade;

class Project extends Model
{
  public function __constract(){
    parent::__constract();
  }
  /**
	 * 实例化模型时, 可批量赋值属性白名单
	 *
	 * @var array
	 */
	protected $fillable = [
		"financier_id","financier_id","financier_name","projects_name","finance_range","finance_money",
		"gift_check","gift_cate","gift_money_auto","collateral_id","new_projects","project_type_template_id","sn",
		"finance_time_cate","finance_time_num","finance_rule_money","finance_rule_fold","rate_search",
		"collateral_code","full_code","full_num","start_time","end_time","profits_cate","rate","collateral",
		"collateral_tmp","is_plan","repayment","invest_cate","status","sort","published_at","auto_rate","is_notice",
    "notice_id","notice_time","collateral_licence_no","trade_finish_date","invest_finish_date","collateral_type"
	];
  protected $validatorRules = [
    'financier_id' => 'required',
    'finance_time_num'=>'required',
    'full_num'=>'required'
  ];

  /**
   * 模糊查询项目记录
   *
   * @param array $options
   * @param int $pagesize
   * @return mixed
   */
  public static function paging_query(array $options, int $pagesize = 15)
  {

    $query = Project::query();

    //判断参数 追加查询条件
    if(isset($options['search']) && !empty($options['search'])){
      $condition = '%'.$options['search'].'%';
      $query = $query->where('projects_name', 'like',$condition);
    }
    if(isset($options['type_id']) && !empty($options['type_id'])){
      $query = $query->where('projects_code', '=',$options['type_id']);
    }
    if(isset($options['status']) && !empty($options['status'])){
      $query = $query->where('status', '=',$options['status']);
    }
    if(isset($options['name']) && !empty($options['name'])){
      $query = $query->where('financier_name', 'like','%'.$options['name'].'%');
    }

    return $query->orderBy('created_at','desc')->paginate($pagesize);
  }
  /**
   * 项目属性
   * @return [type] [description]
   */
  public function projectAttr($data_attr,$image){
    //项目属性
    $attr_data=array();
    foreach ($data_attr['attr'] as $attr_id=>$item) {
      $attr=ProjectTypeTemplateAttribute::find($attr_id);
      if($attr && $attr->template_attribute==0){
        foreach ($item as $value) {
          $attr_data[]=array('sort'=>$attr->sort,'attr_id'=>$attr_id,'project_id'=>$this->id,'cate'=>$attr->template_attribute,'attr_name'=>$attr->name,'content'=>$value);
        }
      }
      ProjectAttr::where('project_id','=',$this->id)->where('attr_id',$attr_id)->delete();
    }
    //上传图片
    if($image){
      foreach ($image as $attr_id => $item) {
        $attr=ProjectTypeTemplateAttribute::find($attr_id);
        $row=array('sort'=>$attr->sort,'attr_id'=>$attr_id,'project_id'=>$this->id,'cate'=>$attr->template_attribute,'attr_name'=>$attr->name);
        $content=array();
        foreach ($item as $value) {
          if(empty($value)){break;}
          $json = upload_file($value);//上传文件
          if($json['code'] == 10000) {
            $content[] =$json['file'];
          }else{abort(500);}
          ProjectAttr::where('project_id','=',$this->id)->where('attr_id',$attr_id)->delete();
        }
        if(!empty($content)){
          $row['content']=json_encode($content);
          $attr_data[]=$row;
        }
      }
    }
    return $attr_data;
  }
  /**
   * 自动结束项目
   * @return [type] [description]
   */
  public static function updateProject(){
    try {
      // DB::beginTransaction();
      // //时间到期的，判断满标条件(三种情况)不满足的，流标
      // $project=DB::select("UPDATE `projects` SET `status` = 'fail', `updated_at` = '".date('Y-m-d H:i:s')."' WHERE status='rush' and  `end_time` <= '".date('Y-m-d H:i:s')."' AND (
      //   (`full_code` = 'pc' AND `full_num` >= finance_money/financed_money*100) OR 
      //   (`full_code` = 'time' AND `full_num` >= '".date('Y-m-d H:i:s')."') OR 
      //   (`full_code` = 'money' AND `full_num` >= 'financed_money')
      //   )");
      DB::commit();
    } catch (Exception $e) {
      DB::rollback();
    }
  }
  /**
   * 撤销项目(已流标的)
   * @return [type] [description]
   */
  public static function faileProject($id){
    $project=Project::find($id);
    if($project->status=='fail'){
      $list=ProjectsUser::where('projects_id',$id)->get();
      $gift_money=0;//红包投资金额
      //修改流水记录
      TradeRecords::where('project_id',$id)->update(['status'=>2,'end_time'=>date('Y-m-d H:i:s')]);
      $trade_list='';
      foreach ($list as $key=>$item) {
        $str=createSn().'~'.$item->sn.'~代收撤销';
        if($key>0){$str='$'.$str;}
        $trade_list.=$str;
        //判断是否为红包投资,更改红包状态
        if(!empty($item->gift)){
          $gift_money+=GiftReceive::whereIn('id',explode(',',$item->gift))->sum('money');
          GiftReceive::whereIn('id',explode(',',$item->gift))->update(['status'=>0,'use_time'=>null]);
        }
      }
      //代收撤销投资金
      $sn=createSn();
      $data=['out_request_no'=>$sn,'trade_list'=>$trade_list];
      $result=CancelPreAuthTrade::send($data);
      Log::info('代收撤销');
      Log::info($result);
      if($result['response_code']!='APPLY_SUCCESS'){
        Log::info('代收撤销'.$result['response_message']);
      }

      //代付红包金额
      if($gift_money>0){
        $data1=[
          'out_trade_no'=>createSn(),
          'out_trade_code'=>'2001',
          'payee_identity_id'=>config('sinapay.payer_id'),
          'payee_identity_type'=>config('sinapay.payer_type'),
          'account_type'=>config('sinapay.gift_payer_account'),
          'amount'=>$gift_money,
          'split_list'=>'',
          'summary'=>'代付红包投资金额',
        ];
        $result=CreateSingleHostingPayTrade::send($data1);
        Log::info('代付红包金额');
        Log::info($result);
        if($result['response_code']!='APPLY_SUCCESS'){Log::info('代付红包金额出错');}
      }
    }
  }

  /**
   * 获取所有的项目类型
   * @return [type] [description]
   */
  public static function getTypes(){
  	return ProjectTypeTemplate::get();
  }
  /**
   * 获取项目的所有状态
   */
  public static function getStatus(){
    return Code::where("type_id","=","project_status")->get();
  }
  /**
   * 项目类型
   */
  public function type(){
  	return ProjectTypeTemplate::where("id","=",$this->project_type_template_id)->first();
  }
  /**
   * 所有的担保方式
   */
  public static function getPromises(){
  	$code=new Code();
    return $code->where("type_id","=","promise_type")->get();
  }
  /**
   * 查看担保方式
   */
  public function collateral(){
    return Code::findByCodeAndTypeId($this->collateral, 'promise_type');
  }
  /**
   * 查看担保机构
   * @return [type] [description]
   */
  public function collateralUser(){
    return User::where('id',$this->collateral_id)->first();
  }
  /**
   * 查看分润信息
   * @return [type] [description]
   */
  public function profits(){
    return Profit::where("id","=",$this->profits_cate)->first();
  }
  /**
   * 查看模板
   */
  public function template($id){
    return Information::find($id);
  }
  /**
   * 红包发放活动
   */
  public function gift(){
    return GiftActivity::find($this->gift_cate);
  }
  /**
   * 查看项目状态
   */
  public function status(){
    return Code::findByCodeAndTypeId($this->status, 'project_status');
  }
  //三方机构类型
  public function collateralType(){
    return Code::findByCodeAndTypeId($this->collateral_type, 'collateral_type');
  }
  /**
   * 录入sian标
   * @return [type] [description]
   */
  public function sina_project(){
    //预计还款的期限
    $term=time();
    //天
    if($this->finance_time_cate=='d'){
      $term=strtotime('+'.$this->finance_time_num.' day',$term);
    }
    //月
    if($this->finance_time_cate=='m'){
      $term=strtotime('+'.($this->finance_time_num*30).' day',$term);
    }
    //自然月
    if($this->finance_time_cate=='mm'){
      $term=strtotime('+'.$this->finance_time_num.' month',$term);
    }

    $financer=User::find($this->financier_id);//借款人
    $repay_method='';//还款方式
    if($this->repayment=='sit'){
      $repay_method='DEBT_MATURITY';
    }
    if($this->repayment=='month'){
      $repay_method='MONTHLY_PAYMENT';
    }
    //担保方式
    $guarantee_method='无担保';
    if($this->collateral_type=='collateral_type_1' && $this->collateral_type=='collateral_type_2'){
      $guarantee_method=$this->suretyCompany()->company_name;
    }
    //投资人列表
    // $investor_list=array();
    // $project_users=ProjectsUser::join('users','users.id','=','projects_user');
    $sina_data=[
      'goods_id'=>$this->sn,
      'goods_name'=>$this->projects_name,
      'annual_yield'=>$this->rate_search,
      'term'=>date('YmdHis',$term),
      'repay_method'=>$repay_method,
      'guarantee_method'=>$guarantee_method,
      'debtor_list'=>$financer->identity_id.'^UID^'.$this->finance_money,
      'investor_list'=>'',
      'total_amount'=>$this->finance_money,
      'begin_date'=>date('YmdHis',strtotime($this->start_time)),
      'url'=>'https://www.ibeibeili.com/oneProjects/'.$this->id,
    ];
    return CreateP2pHostingBorrowingTarget::send($sina_data);
  }
}